<template>
	<div ref="el" class="flex-1 flex flex-col">
		<div class="mt-2 mb-[10px] flex justify-between items-center">
			<my-bets-tabs
				v-model="tab"
				:cashout-num="cashoutList.length"
				:live-num="liveList.length"
				:unsettled-num="unsettlementList.length" />
			<my-bets-time
				class="shrink-0"
				:tab="tab"
				v-model:cashout-sort-by-match-time="cashoutSortByMatchTime"
				v-model:live-sort-by-match-time="liveSortByMatchTime"
				v-model:unsettled-sort-by-match-time="unsettledSortByMatchTime"
				v-model:settled-date-range="settledDateRange"
				v-model:all-date-range="allDateRange" />
		</div>
		<base-list-plus
			class="flex-1"
			:loading="loading"
			:isFinish="isFinish"
			:isEmpty="list.length === 0"
			@load="search">
			<base-waterfall :data="list" :column="cols" :picturePreReading="false">
				<template v-slot="{ item, width }">
					<my-bets-item
						:data="item"
						:early-settlement-status="getEarlySettlementStatus(item)"
						:early-settlement-amount="getEarlySettlementAmount(item)"
						:style="{ width }"
						@settlement="init" />
				</template>
			</base-waterfall>
		</base-list-plus>
	</div>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import { SPORTS_MY_BETS_TAB } from '@/constants'
import { setItem, getItem, getItemById } from '@/utils'
import { getFromDate, getToDate, compareByMatchTime, filterByBetTime } from './util'
import { SportsMyBetsTab } from './types'
import { BetType } from '@/types'
import { getBetList, getCashouts } from '@/api/betting'
import { useListCols, useRequest } from '@/hooks'
import { useAppStore } from '@/store'
import { BettingStatus, SettlementStatus } from '@/enums'
import MyBetsTabs from './my-bets-tabs.vue'
import MyBetsItem from './my-bets-item.vue'
import MyBetsTime from './my-bets-time.vue'
import { BaseWaterfall, BaseListPlus } from '@/components/base'

const appStore = useAppStore()

const tab = ref(getItem(SPORTS_MY_BETS_TAB) || SportsMyBetsTab.cashout)

const cashoutSortByMatchTime = ref(false)
const liveSortByMatchTime = ref(false)
const unsettledSortByMatchTime = ref(false)

const settledDateRange = ref<[number, number] | null>(null)
const allDateRange = ref<[number, number] | null>(null)

const el = ref(null)

const { cols } = useListCols(el)

const { run: runCashouts, data: cashouts, loading: loadingCashout } = useRequest(getCashouts)

const {
	run: runUnsettlement,
	loading: loadingUnsettlement,
	list: unsettlementList
} = useRequest<BetType>(getBetList, {
	pageSize: 100,
	onSuccess: () => {
		if (unsettlementList.value.length) {
			const items = unsettlementList.value.map((item: any) => {
				const { betOrderId, createdAt, bonus } = item
				return { betOrderId, createdAt, bonusId: bonus.bonusId }
			})
			runCashouts({ items })
		}
	}
})

const {
	run: runSettlemented,
	loading: loadingSettlemented,
	list: settlementedList,
	isFinish: isFinishSettlemented
} = useRequest<BetType>(getBetList, {
	pageSize: 12
})

const getEarlySettlementStatus = (item: BetType) =>
	getItemById<{ earlySettlementStatus: SettlementStatus }>(
		cashouts.value,
		item.betOrderId,
		'betOrderId'
	)?.earlySettlementStatus

const getEarlySettlementAmount = (item: BetType) =>
	getItemById<{ earlySettlementAmount: number }>(cashouts.value, item.betOrderId, 'betOrderId')
		?.earlySettlementAmount

const loading = computed(
	() =>
		loadingUnsettlement.value ||
		loadingSettlemented.value ||
		(tab.value === SportsMyBetsTab.cashout && loadingCashout.value)
)

const cashoutList = computed(() =>
	unsettlementList.value.filter(
		(item) =>
			getItemById<{ earlySettlementStatus: SettlementStatus }>(
				cashouts.value,
				item.betOrderId,
				'betOrderId'
			)?.earlySettlementStatus === SettlementStatus.available
	)
)

const liveList = computed(() =>
	unsettlementList.value.filter(({ selections }) => selections.some(({ isLive }) => isLive))
)

const list = computed(() => {
	let res: BetType[] = []
	let sortByMatchTime = false
	let dateRange: any[] | null = []
	if (tab.value === SportsMyBetsTab.cashout) {
		res = cashoutList.value
		sortByMatchTime = cashoutSortByMatchTime.value
	} else if (tab.value === SportsMyBetsTab.live) {
		res = liveList.value
		sortByMatchTime = liveSortByMatchTime.value
	} else if (tab.value === SportsMyBetsTab.unsettled) {
		res = unsettlementList.value
		sortByMatchTime = unsettledSortByMatchTime.value
	} else if (tab.value === SportsMyBetsTab.settled) {
		res = settlementedList.value
		dateRange = settledDateRange.value
	} else {
		res = [...unsettlementList.value, ...settlementedList.value]
		dateRange = allDateRange.value
	}
	if (sortByMatchTime) {
		return [...res].sort(compareByMatchTime)
	} else if (dateRange?.length) {
		return res.filter((item) => filterByBetTime(item, dateRange))
	}
	return res
})

const isFinish = computed(() => {
	if (
		[SportsMyBetsTab.cashout, SportsMyBetsTab.live, SportsMyBetsTab.unsettled].includes(tab.value)
	) {
		return true
	} else {
		return isFinishSettlemented.value
	}
})

const search = (refresh = false) => {
	if (![SportsMyBetsTab.settled, SportsMyBetsTab.all].includes(tab.value)) {
		return
	}
	const dateRange =
		tab.value === SportsMyBetsTab.settled ? settledDateRange.value : allDateRange.value
	runSettlemented(
		{
			locale: appStore.lang,
			status: BettingStatus.settlemented,
			orderBy: 'settled_at',
			fromDate: getFromDate(dateRange),
			toDate: getToDate(dateRange)
		},
		{ refresh }
	)
}

watch(tab, (val) => {
	setItem(SPORTS_MY_BETS_TAB, val)
})

watch([tab, settledDateRange, allDateRange], () => {
	init()
})

const init = () => {
	runUnsettlement(
		{
			locale: appStore.lang,
			status: BettingStatus.betSuccessed,
			isAll: true
		},
		{ refresh: true }
	)
	search(true)
}

init()
</script>
